<template>
  <el-dialog width="1000px" :visible="showDialog" :title="id === 0 ? '新建采购单' : '修改采购单'" center :before-close="handleClose"
    @open="loadData(id)">
    <el-row :gutter="10">
      <el-col :span="12">
        <el-card>
          <el-form label-position="left" label-width="60px" ref="itemForm" :rules="rules" :model="item">
            <el-form-item label="名称" prop="name">
              <el-input v-model="item.name" placeholder="请输入资产名称"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="cid" >
              <el-cascader v-model="item.cid" clearable
                :options="categoryGroup" :props="{ expandTrigger: 'hover', label: 'name', value: 'id', emitPath: false }">
              </el-cascader>
            </el-form-item>
            <el-form-item label="品牌" prop="brandId">
              <el-select v-model="item.brandId" clearable>
                <el-option v-for="brand in brands" :key="brand.id" :label="brand.name" :value="brand.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input v-model.number="item.price" placeholder="请输入产品单价"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="number">
              <el-input v-model.number="item.number" placeholder="请输入购置数量"></el-input>
            </el-form-item>
            <el-form-item label="说明" prop="desc">
              <el-input type="textarea" placeholder="采购备注" v-model="item.desc" rows="2"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="add()">新增采购项</el-button>
              <el-button type="warning" @click="reStart()">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div class="data-table">
            <el-table :data="list" height="361.6px" size="mini" @row-click="updateItem">
              <el-table-column label="名称" min-width="60" prop="name"></el-table-column>
              <el-table-column label="分类" min-width="60" prop="cid" :formatter="row => categoryMap.get(row.cid)" show-overflow-tooltip></el-table-column>
              <el-table-column label="品牌" min-width="60" prop="brandId" :formatter="row => brandMap.get(row.brandId)" show-overflow-tooltip></el-table-column>
              <el-table-column label="单价" width="60" prop="price"></el-table-column>
              <el-table-column label="数量" width="60" prop="number"></el-table-column>
              <el-table-column width="40">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-close" size="mini" @click="removeItem(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="padding: 22px 0;">
            <el-button type="primary" @click="submit()">提交</el-button>
            <el-button type="warning" @click="clear()">清空</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import * as purchase from '@/api/purchase'

import rules from '@/validator/purchase.js'
import * as common from '@/common.js'

export default {
  name: 'PurchaseForm',
  props: ['showDialog', 'id', 'categoryGroup', 'categoryMap', 'brandMap', 'brands'],
  data () {
    return {
      item: {},
      list: [],
      rules
    }
  },
  methods: {
    loadData (id) {
      if (this.$refs.itemForm) {
        this.$refs.itemForm.resetFields()
      }
      if (id !== 0) {
        console.log(`[purchase-form:load-data:id]: ${id}`)
        /* 获取需更新的数据 */
        purchase.selectById(id).then(resp => {
          this.list = JSON.parse(resp.data.list)
        }).catch(() => {
          this.$notify.error('请求数据失败')
        })
      }
    },
    close () {
      this.list = []
      this.item = {}
      this.$emit('update:showDialog', false)
    },
    handleClose (done) {
      this.$confirm('确认关闭？').then(() => {
        this.close()
        done()
      }).catch(() => {})
    },
    // 重置表单
    reStart () {
      this.$refs.itemForm.resetFields()
    },
    // 新增表单项
    add () {
      this.$refs.itemForm.validate(vaild => {
        if (vaild) {
          this.list.push({...this.item})
          this.reStart()
        } else {
          this.$message.warning('表单验证未通过！')
        }
      })
    },
    removeItem (index) {
      this.list.splice(index, 1)
    },
    updateItem (row) {
      this.item = {...row}
    },
    submit () {
      if (this.list.length === 0) {
        this.$message.warning('至少存在一个采购项')
        return
      }
      // 提交
      let data = { list: common.toJsonString(this.list) }
      if (this.id === 0) {
        // 新增
        let funds = []
        this.list.forEach(e => {
          funds.push(e.price * e.number)
        })
        // 计算总金额
        let applyFund = funds.reduce((a, b) => a + b)
        // 提交数据
        purchase.insert(applyFund, data).then(resp => {
          this.$notify.success('新增成功')
          this.$emit('success')
          this.close()
        }).catch(() => {
          this.$notify.error('新增失败')
        })
      } else {
        // 修改
        data.id = this.id
        purchase.update(data).then(resp => {
          this.$notify.success('更新成功')
          this.$emit('success')
          this.close()
        }).catch(() => {
          this.$notify.error('更新失败')
        })
      }
    },
    clear () {
      this.list = []
    }
  }
}
</script>

<style scoped>
  .data-table {
    border: 1px solid gainsboro;
  }

  .data-table td {
    padding: 2px 0;
  }
</style>
